﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Collections;
using static PongChong.Fun.BingWall.Wallpaper;

namespace PongChong.Fun.BingWall
{
    public class BingWall
    {
        private static string BingWallUrl = "http://www.bing.com/HPImageArchive.aspx?format=js&idx={0}&n=8";

        private static int current_index = 7;

        public static string RandomDownload()
        {
            var url = getNextUrl();

            using (WebClient client = new WebClient())
            {
                client.Encoding = System.Text.Encoding.UTF8;
                return client.DownloadString(new Uri(url));
            }
        }

        private static string getNextUrl()
        {
            string url = string.Format(BingWallUrl, current_index.ToString());
            current_index -= 1;
            if (current_index == -1) current_index = 7;
            return url;
        }

        public static Rootobject GetRandomImage()
        {
            var r = RandomDownload();
            return JsonConvert.DeserializeObject<Rootobject>(r);
        }

        public static bool DownloadImage(string url, string savePath)
        {
            using (var client = new WebClient())
            {
                client.DownloadFile(url, savePath);
            }

            return System.IO.File.Exists(savePath);
        }

        public static void SetWallpaper(Uri uri, Style style)
        {
            Wallpaper.Set(uri, style);
        }
    }
}
